package com.nitty.cash.loop.ui.fragment

import android.graphics.BitmapFactory
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonFragment
import com.nitty.cash.loop.databinding.UiPageTabWithdrawBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.activity.ApplyAct
import com.nitty.cash.loop.ui.activity.LimitRejectedAct
import com.nitty.cash.loop.ui.activity.LimitReviewingAct
import com.nitty.cash.loop.ui.activity.OrderListAct
import com.nitty.cash.loop.ui.activity.PermissionAppListSmsAct
import com.nitty.cash.loop.ui.activity.ProcessAct
import com.nitty.cash.loop.ui.dialog.NittyTipsDialog
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.WithdrawPresenter
import com.nitty.cash.loop.utils.helper.NittyOrderHelper
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import org.json.JSONObject
import java.math.BigDecimal

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：主页
 */
class TabWithdrawFragment: CommonFragment(), IViewContract.IWithdrawView {
    lateinit var binding: UiPageTabWithdrawBinding
    var presenter: WithdrawPresenter? = null
    override fun getNittyRootView(inflater: LayoutInflater): View {
        binding = UiPageTabWithdrawBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        setNittyTitleBarVisibility(View.VISIBLE)
        setNittyBackBtnVisibility(View.GONE)
        setNittyTextTitleVisibility(View.GONE)
        setNittyRightBtnRes(R.mipmap.img_customer_white)
        setNittyRootBackgroundLableRes(R.mipmap.nitty_withdraw_titlebar_bg)
        setNittyRootParentBackgroundColors(Color.parseColor("#ffffd451"), Color.parseColor("#ffffac17"))
        binding.withDrawRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.withdrawContentLayout.visibility = View.INVISIBLE
    }

    override fun initNittyListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Home Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"Home Page")
        }
        binding.withDrawRefreshLayout.setOnRefreshListener {
            publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESH))
            publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_ORDER_REFRESH))
        }
        binding.btnWithdrawAvailableCredit.setOnClickListener {
            presenter?.checkNittyWithdrawPermissionsAgree()
        }

        //订单列表
        binding.orderListLayout.setOnClickListener {
            onIntent(OrderListAct::class.java)
        }
    }

    override fun loadNittyData() {
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_WITHDRAW_START)
        if (presenter == null){
            presenter = WithdrawPresenter(this)
        }
    }

    /**
     * 未授信页面
     */
    override fun showNittyStepIncompleteViews() {
        binding.withdrawContentLayout.visibility = View.VISIBLE
        binding.textWithdrawExpirse.text = String.format(getString(R.string.withdraw_expires),"**/**/****")
        binding.imgWithdrawExpirseTips.visibility = View.GONE
        binding.textWithdrawAmount.text = "***,***"
        binding.textWithdrawMinAmount.text = "0"
        binding.textWithdrawMaxAmount.text = "**,***"
        binding.btnWithdrawAvailableCredit.text = getString(R.string.withdraw_activate)
        binding.btnWithdrawAvailableCredit.isEnabled = true
        binding.withdrawUsedLimitLayout.visibility = View.GONE

        //动画效果
        binding.circleSeekBar.progress = 0
        binding.circleSeekBar.max = 1000
        binding.circleSeekBar.showAnimation(1000, 0, 1000)
        //禁止拖拽
        binding.circleSeekBar.isEnabledDrag = false
        //设置游标
        binding.circleSeekBar.setCursorThumbBitmap(BitmapFactory.decodeResource(resources, R.mipmap.nitty_amount_cursor_normal))
    }

    /**
     * 授信已完成
     */
    override fun showNittyStepCompleteViews(data: JSONObject) {
        binding.withdrawContentLayout.visibility = View.VISIBLE
        binding.textWithdrawExpirse.text = String.format(getString(R.string.withdraw_expires),NittyProcessHelper.getAuthCreditExpireDate())
        binding.imgWithdrawExpirseTips.visibility = View.VISIBLE

        val availableAmount = BigDecimal(data.optString("availableAmount")).stripTrailingZeros().toPlainString()
        val minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString()
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        binding.textWithdrawMinAmount.text = minAmount
        binding.textWithdrawMaxAmount.text = maxAmount
        binding.textWithdrawAmount.text = availableAmount
        binding.btnWithdrawAvailableCredit.text = getString(R.string.withdraw_available)
        binding.btnWithdrawAvailableCredit.isEnabled = availableAmount.toInt() > 0
        binding.withdrawUsedLimitLayout.visibility = View.VISIBLE

        //已使用额度
        binding.textUsedAmount.text = BigDecimal(data.optString("utilisedAmount")).stripTrailingZeros().toPlainString()
        //单位
        binding.textUsedAmountUnit.text = data.optString("currency")
        //订单数量
        binding.textWithdrawOrderCount.text = NittyOrderHelper.getNittyOrderOtherList().size.toString()

        //动画效果
        binding.circleSeekBar.progress = availableAmount.toInt()
        binding.circleSeekBar.max = maxAmount.toInt()
        binding.circleSeekBar.showAnimation(0, availableAmount.toInt(), 1000)
        binding.circleSeekBar.isEnabledDrag = false
        //设置游标
        binding.circleSeekBar.setCursorThumbBitmap(BitmapFactory.decodeResource(resources, R.mipmap.nitty_amount_cursor_pressed))
    }

    /**
     * 权限
     */
    override fun showNittyPermissionPage() {
        onIntent(PermissionAppListSmsAct::class.java)
    }

    /**
     * 申贷
     */
    override fun showNittyApplyPage() {
        ApplyAct.start(requireContext())
    }

    /**
     * 填写进件信息
     */
    override fun showNittyStepsPage() {
        onIntent(ProcessAct::class.java)
    }

    /**
     * 授信拒绝
     */
    override fun showNittyCreditRejectedPage() {
        onIntent(LimitRejectedAct::class.java)
    }

    /**
     * 授信额度审核中
     */
    override fun showNittyCreditReviewPage() {
        onIntent(LimitReviewingAct::class.java)
    }

    /**
     * 存在被拒绝的订单提示
     */
    override fun showNittyOrderRejectedDialog() {
        val againApplyDate = NittyProcessHelper.getAuthApplyAgainDate()
        val showText = String.format(getString(R.string.dialog_apply_error_tips),againApplyDate)
        val spString = SpannableString(showText)
        val start = showText.indexOf(againApplyDate)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFD5118")), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        val errorDialog = NittyTipsDialog(requireContext(),"Order Rejected")
        errorDialog.setCancelable(true)
        errorDialog.setCanceledOnTouchOutside(true)
        errorDialog.show()
        errorDialog.setTipsIconResource(R.mipmap.nitty_order_rejected_error_tips_icon)
        errorDialog.setBtnOkText(getString(R.string.click_ok))
        errorDialog.setBtnCancelText(getString(R.string.click_cancel))
        errorDialog.setTipsText(spString)

    }

    override fun onNittyPublishEvent(event: NittyEventData) {
        super.onNittyPublishEvent(event)
        binding.withDrawRefreshLayout.isRefreshing = false
        when(event.eventType){
            NittyEventData.TYPE.NITTY_PROCESS_REFRESHED -> { //刷新流程完成
                presenter?.queryNittyCreditStatusAction()
            }
            NittyEventData.TYPE.NITTY_ORDER_REFRESHED -> {//订单刷新完成
                binding.textWithdrawOrderCount.text = NittyOrderHelper.getNittyOrderOtherList().size.toString()
            }
            else -> {

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_WITHDRAW_END)
    }
}